package com.meiyuetao.myt.sale.web.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;
import lab.s2jh.core.web.view.OperationResult;
import lab.s2jh.sys.entity.AttachmentFile;
import lab.s2jh.sys.service.AttachmentFileService;
import lab.s2jh.web.action.BaseController;

import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.service.BoxOrderService;

@MetaData("天猫订单附件管理")
public class TmallOrderFileController extends BaseController<AttachmentFile, String> {

    @Autowired
    private AttachmentFileService attachmentFileService;

    @Autowired
    private BoxOrderService boxOrderService;

    private File file;

    private String[] filesFileName;

    private String[] filesContentType;

    @Override
    protected BaseService<AttachmentFile, String> getEntityService() {
        return attachmentFileService;
    }

    @Override
    protected void checkEntityAclPermission(AttachmentFile entity) {
        // Do nothing check
    }

    public HttpHeaders upLoadNew() {
        return buildDefaultHttpHeaders("inputBasic");
    }

    @MetaData(value = "多文件上传")
    public HttpHeaders uploadMulti() {
        System.out.println(file.toString());
        List<String> cvs = importCsv(file);
        cvs.remove(0);// 去除标题行
        for (String line : cvs) {
            List<String> cols = parseCSV(line);
            importLine(cols);
        }
        setModel(OperationResult.buildSuccessResult("导入完成"));
        return buildDefaultHttpHeaders();
    }

    public void importLine(List<String> cols) {
        String tid = cols.get(0);// 订单号
        String receivePerson = cols.get(12);// 收货人姓名
        String deliveryAddr = cols.get(13);// 收货地址
        String mobilePhone = cols.get(16).replace("\'", "");// 联系手机
        BoxOrder boxOrder = boxOrderService.findByOrderSeq(tid);

        if (boxOrder != null && isDecimalNumber(tid)) {
            boxOrder.setReceivePerson(receivePerson);
            boxOrder.setDeliveryAddr(deliveryAddr);
            boxOrder.setMobilePhone(mobilePhone);
            System.out.println("订单号：" + tid + "\t收货人姓名：" + receivePerson + "\t收货地址：" + deliveryAddr + "\t联系手机：" + mobilePhone);

            boxOrderService.save(boxOrder);
        } else {
            Validation.isTrue(false, "无法识别的订单号：" + tid);
        }
    }

    public ArrayList<String> parseCSV(String lineStr) {
        ArrayList<String> colList = new ArrayList<String>();
        StringBuffer sb = new StringBuffer(lineStr);
        int colFlg = 0;
        boolean comaFlg = false;
        StringBuffer colBuf = new StringBuffer();
        while (sb.length() > 0) {
            char c = sb.charAt(0);
            if (comaFlg == false) {
                if (c == ',') {
                    colList.add(colBuf.toString());
                    colBuf = new StringBuffer();
                } else if (c == '\"') {
                    colFlg = 1;
                    char tmpc = '\0';
                    if (sb.length() > 1) {
                        tmpc = sb.charAt(1);
                    }
                    if (tmpc == '\"') {
                        colFlg = 2;
                        sb.deleteCharAt(1);
                    }
                    comaFlg = true;
                } else {
                    colFlg = 2;
                    colBuf.append(c);
                    comaFlg = true;
                }
            } else {
                if (colFlg == 2 && c == ',') {
                    colList.add(colBuf.toString());
                    colBuf = new StringBuffer();
                    comaFlg = false;
                } else if (colFlg == 1 && c == '\"') {
                    char tmpc = '\0';
                    if (sb.length() > 1) {
                        tmpc = sb.charAt(1);
                    }
                    if (tmpc == '\"') {
                        colBuf.append(tmpc);
                        sb.deleteCharAt(1);
                    } else {
                        colFlg = 2;
                    }
                } else {
                    colBuf.append(c);
                }
            }
            sb.deleteCharAt(0);
        }
        colList.add(colBuf.toString());
        return colList;
    }

    /**
     * 判断是不是数字
     * 
     * @param number
     * @return
     */
    public boolean isDecimalNumber(String number) {
        Pattern p = Pattern.compile("^[0-9]*$");
        Matcher m = p.matcher(number);
        return m.find();
    }

    /**
     * 导入
     * 
     * @param file
     *            csv文件(路径+文件)
     * @return
     */
    public List<String> importCsv(File file) {
        List<String> dataList = new ArrayList<String>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            String line = "";
            while ((line = br.readLine()) != null) {
                dataList.add(line);
            }
        } catch (Exception e) {
        } finally {
            if (br != null) {
                try {
                    br.close();
                    br = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dataList;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String[] getFilesFileName() {
        return filesFileName;
    }

    public void setFilesFileName(String[] filesFileName) {
        this.filesFileName = filesFileName;
    }

    public String[] getFilesContentType() {
        return filesContentType;
    }

    public void setFilesContentType(String[] filesContentType) {
        this.filesContentType = filesContentType;
    }
}